package com.kantboot.system.user.user.service.impl;

import com.kantboot.system.user.role.domain.dto.UserRoleSaveDTO;
import com.kantboot.system.user.role.domain.entity.SysUserRole;
import com.kantboot.system.user.role.service.ISysUserRoleService;
import com.kantboot.system.user.setting.SystemUserSetting;
import com.kantboot.system.user.user.dao.repository.SysUserRepository;
import com.kantboot.system.user.user.domain.entity.SysUser;
import com.kantboot.system.user.user.service.ISysUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserServiceImpl implements ISysUserService {

    @Resource
    private SysUserRepository repository;

    @Resource
    private ISysUserRoleService userRoleService;

    @Resource
    private SystemUserSetting systemUserSetting;

    @Override
    public SysUser createUser(SysUser user) {
        // 将user的id设置为null，强制数据库自增
        user.setId(null);
        // 将user的isInit设置为false，强制用户不是初始化用户
        user.setIsInit(false);
        // 将user的isTemporary设置为true，强制用户是临时用户
        user.setIsTemporary(true);
        // 保存用户
        SysUser result = repository.save(user);

        // 默认角色编码
        String defaultRoleCode = systemUserSetting.getDefaultRoleCode();

        // 为用户添加默认角色
        UserRoleSaveDTO dto = new UserRoleSaveDTO();
        dto.setUserId(result.getId())
                .setUserRoles(List.of(
                        new SysUserRole().setRoleCode(defaultRoleCode).setIsVisible(true)));

        userRoleService.saveUserRole(dto);

        result = repository.save(user);
        return result;
    }

    @Override
    public SysUser getUserByUsername(String username) {
        return repository.findByUsername(username);
    }
}
